# encoding:utf-8
# user: ares at 18-9-10

from pymongo import MongoClient
import matplotlib.pyplot as plt
import numpy as np

def getAvgPrice(diqu,laiyuan):
    '''
    获取一个区的平均价
    :param diqu:
    :return:
    '''
    dict={'diqu':diqu}
    if laiyuan!='':
        dict['laiyuan']=laiyuan

    col=connect()
    #print(type(col))
    pipeline2=[
        {'$match':dict},
        {'$group':{'_id':'$diqu','total_price':{'$sum':'$price'},'total_area':{'$sum':'$area'}}}
    ]

    totalPrice=col.aggregate(pipeline2)
    dictTotle=list(totalPrice)[0]
    #totalArea=col.aggregate([{'$group':{'_id':'$diqu','total_area':{'$sum':'$area'}}}])
    #print(dictTotle)
    totalPrice2=dictTotle['total_price']
    totalArea2=dictTotle['total_area']
    return totalPrice2/totalArea2

def getTotalAvgPrice(laiyuan):
    totalAvgPrice=[]
    diqu=getdiqu()
    for index,d in enumerate(diqu):
        avgPrice=round(getAvgPrice(d,laiyuan),3)
        totalAvgPrice.append({'name':d,'value':avgPrice})
    return totalAvgPrice

def getdiqu():
    diqu=['福田','罗湖','南山','盐田','宝安','龙华','龙岗','大鹏','光明','坪山']
    return diqu

def getCol(where):
    col=connect()
    return col.find(where)

def connect():
    client=MongoClient('localhost:27017',connect=True)
    db=client['test']
    collection=db['zfdb']
    return collection

#获取各区每平米租金
def getBar():
    lianjia_totalAvgPrice=getTotalAvgPrice('链家')
    fangtianxia_totalAvgPrice=getTotalAvgPrice('房天下')

    #plt.xlabel('区域',fontproperties='FangSong',fontsize=10)
    plt.ylabel('单位（元/每平米）',fontproperties='FangSong',fontsize=10)
    plt.title("深圳各区每平米租金",fontproperties='FangSong',fontsize=15)

    data_lj={x['name']:x['value'] for x in lianjia_totalAvgPrice}
    data_ftx = {x['name']: x['value'] for x in fangtianxia_totalAvgPrice}

    len_x=len(data_lj)
    xticks=getdiqu()

    index=np.arange(len_x)

    bar_width=0.35

    renta=plt.bar(index,[data_lj.get(xtick,0) for xtick in xticks],width=bar_width)
    rentb = plt.bar(index+bar_width, [data_ftx.get(xtick, 0) for xtick in xticks], width=bar_width)
    plt.xticks(index+bar_width,xticks)

    #plt.bar(totalAvgPrice)
    #增加图例
    plt.legend((renta,rentb),('链家','房天下'))

    #plt.figure(dpi=400)
    #plt.savefig('test', dpi=600)
    plt.ylim(0.40)
    plt.show()

#各区中的各街道每平米房租
def getDistAvgPrice(diqu,laiyuan):
    dist={'diqu':diqu}
    if laiyuan!='':
        dist['laiyuan']=laiyuan

    dictAvg={}

    col=connect()
    pipeline=[
        {'$match':dist},
        {'$group':{'_id':'$jiedao','total_price':{'$sum':'$price'},'total_area':{'$sum':'$area'}}}
    ]
    totalAvgPrice=col.aggregate(pipeline)
    lstAvgPrice=list(totalAvgPrice)

    for avgprice in lstAvgPrice:
        price=avgprice['total_price']/avgprice['total_area']
        jiedao=avgprice['_id']
        dictAvg[jiedao]=round(price,2)
        #print(dictAvg)
    return dictAvg

#各区中各街道的房源数
def getHouseCount(diqu,laiyuan):
    dist={'diqu':diqu}
    if laiyuan!='':
        dist['laiyuan']=laiyuan

    dictCount={}
    col=connect()
    pipeline=[
        {'$match':dist},
        {'$group':{'_id':'$jiedao','count':{'$sum':1}}}
    ]
    totalCount=col.aggregate(pipeline)
    lstCount=list(totalCount)

    for count in lstCount:
        c=count['count']
        jiedao=count['_id']
        dictCount[jiedao]=c

    return dictCount


def getDistAvgPriceBar():
    laiyuan='链家'
    dist='福田'

    dictAvg=getDistAvgPrice(dist,laiyuan)

    ax1=plt.subplot(111)

    #plt.xlabel('位置',fontproperties='SimHei',fontsize=10)
    plt.ylabel('每平米租金（元/每平米）',fontproperties='SimHei',fontsize=10)
    plt.title(dist+'区各位置每平米租金',fontproperties='FangSong',fontsize=15)

    xticks=list(dictAvg.keys())
    lenDist=len(dictAvg)
    index=np.arange(lenDist)

    bar_width=0.5

    renct=plt.bar(index,list(dictAvg.values()),width=bar_width)

    #plt.tick_params(labelsize=10)
    plt.xticks(index,xticks,fontsize=8)
    plt.xticks(rotation=75)

    for rec in renct:
        x=rec.get_x()
        height=rec.get_height()
        ax1.text(x-0.5,1.01*height,str(height),fontsize=2,fontproperties='FangSong')

    plt.legend((renct,),(laiyuan,))
    plt.show()

#叠加
def getDistAvgPrice_MulitBar():
    laiyuan='链家'
    dist='宝安'

    dictAvg=getDistAvgPrice(dist,laiyuan)

    #各街道房源数量
    dictCount=getHouseCount(dist,laiyuan)

    fig=plt.figure(figsize=(12,8))
    ax1=fig.add_subplot(111)

    #x轴标签，及刻度
    xticks=list(dictAvg.keys())
    lenDist=len(dictAvg)
    index=np.arange(lenDist)

    bar_width=0.5

    renct=ax1.bar(index,list(dictAvg.values()),width=bar_width,label=laiyuan)

    plt.xticks(index,xticks,fontsize=10)
    plt.xticks(rotation=75)

    #创建一个独立的y轴，共享X轴，双坐标轴
    ax2=ax1.twinx()

    #设置右y轴坐标刻度范围
    ax2.set_ylim(0,75)
    rencta=ax2.plot(index,list(dictCount.values()),color='r',label='房源数')

    title=dist + '区各位置每平米租金'

    plt.title(title, fontproperties='FangSong', fontsize=15)

    ax1.set_ylabel('每平米租金（元/每平米）', fontproperties='SimHei', fontsize=10)
    ax2.set_ylabel('房源数', fontproperties='SimHei', fontsize=10)

    # for rec in renct:
    #     x=rec.get_x()
    #     height=rec.get_height()
    #     ax1.text(x-0.5,1.01*height,str(height),fontsize=2,fontproperties='FangSong')

    ax1.legend(loc=(.02,.92),shadow=False)
    ax2.legend(loc=(.02,.85),shadow=False)

    plt.savefig(title,dp1=300)
    plt.show()

if __name__ == '__main__':
    # 各区每平米租金
    #getBar()

    #各区中的各街道每平米房租
    #getDistAvgPriceBar()

    #各区中的各街道每平米房租直方图，房源数折线图叠加
    getDistAvgPrice_MulitBar()